﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using log4net;
using Nissen_Common;
using Nissen_Dao;
using Nissen_Manage.Forms;
using Nissen_Marking.Forms;
using Nissen_Model;
using Nissen_Model.Dto;
using Nissen_Resources;
using Utility_Log;

namespace Nissen_StartUp
{

    public partial class LoginForm : Form
    {
                
        public LoginForm()
        {
            InitializeComponent();
            
        }

        private bool SSOFlag = false;//true:machine ; false:Worker
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            string ssoMin = "";
            string ssoMax = "";
            try
            {
            
                if(string.IsNullOrEmpty(this.txtSSO.Text.Trim()))
                {
                    MessageBox.Show(ResourceCommon.GetResource("SSOMustInput"));
                    return;
                }

                var txtSSOLength = this.txtSSO.Text.Trim().Length;
                if(txtSSOLength==9)
                {
                    //GE SSO
                    ssoMin = ConfigurationManager.AppSettings["ssomin"];
                    ssoMax = ConfigurationManager.AppSettings["ssomax"];
                }
                else if (txtSSOLength == 15)
                {
                    //身份证15位
                    if (!CheckCidInfo15(this.txtSSO.Text.Trim()))
                    {
                        MessageBox.Show(ResourceCommon.GetResource("PlaseInputRightID"));
                        return;
                    }
                    ssoMin = ConfigurationManager.AppSettings["pcardmin"];
                    ssoMax = ConfigurationManager.AppSettings["pcardmax"];
                }
                else if (txtSSOLength == 18)
                {
                    //身份证18位
                    if (!CheckCidInfo18(this.txtSSO.Text.Trim()))
                    {
                        MessageBox.Show(ResourceCommon.GetResource("PlaseInputRightID"));
                        return;
                    }
                    ssoMin = ConfigurationManager.AppSettings["pcardmin"];
                    ssoMax = ConfigurationManager.AppSettings["pcardmax"];
                }
                else
                {
                    MessageBox.Show(ResourceCommon.GetResource("PlaseInputRightID"));
                    return;
                }
                
                LoginUser loginUser = new LoginUser();

                loginUser.LoginName = this.txtName.Text.Trim();
                loginUser.LoginSSO = this.txtSSO.Text.Trim();
                LoginFormService loginFormService = new LoginFormService();

                if(SSOFlag )
                {
                    var machine = loginFormService.GetMachine();
                    loginUser.Machine = machine;
                    loginUser.NissenSSO = machine.NissenSSO;
                }
                else
                {
                    var nissenSSO = loginFormService.GetNissenSSO(this.txtSSO.Text.Trim(), ssoMin, ssoMax, this.txtName.Text.Trim());
                    loginUser.NissenSSO = nissenSSO;
                }
                ContextManager.Instance.CurrentUser = loginUser;

                loginFormService.SaveOrUpdateWorkerCache(this.txtSSO.Text.Trim(),this.txtName.Text.Trim());
                this.Hide();
                Thread.Sleep(500);
                if (cobLevel.SelectedIndex == 0)
                {
                    FormMarkSelect formMarkSelect = new FormMarkSelect();
                    formMarkSelect.Show();
                    UserLoginLogService userLoginLogService = new UserLoginLogService();
                    userLoginLogService.SaveLoginLog();
                }
                else
                {
                    ManageMarkSelect manageMarkSelect = new ManageMarkSelect();
                    manageMarkSelect.Show();
                }

                
            }
            catch (Exception ex)
            {

                //记录错误日志
                Log4netManager.Instance.Logs.Error("error", ex);
                MessageBox.Show(ex.Message);
            }
            
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {
            this.cobLevel.Visible = true;
            //this.cobLevel.Visible = false;

            cobLevel.SelectedIndex = 0;
            this.txtSSO.Focus();
            LoginFormService loginFormService = new LoginFormService();
            loginFormService.GetWorkerCache("");
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 校验15位
        /// </summary>
        /// <param name="cid"></param>
        /// <returns></returns>
        private bool CheckCidInfo15(string cid)
        {
            System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(@"^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$");
            System.Text.RegularExpressions.Match mc = rg.Match(cid);
            if (!mc.Success)
            {
                return false;
            }
            return true;

        }

        /// <summary>
        /// 校验18位
        /// </summary>
        /// <param name="cid"></param>
        /// <returns></returns>
        private bool CheckCidInfo18(string cid)
        {
            string[] aCity = new string[] { null, null, null, null, null, null, null, null, null, null, null, "北京", "天津", "河北", "山西", "内蒙古", null, null, null, null, null, "辽宁", "吉林", "黑龙江", null, null, null, null, null, null, null, "上海", "江苏", "浙江", "安微", "福建", "江西", "山东", null, null, null, "河南", "湖北", "湖南", "广东", "广西", "海南", null, null, null, "重庆", "四川", "贵州", "云南", "西藏", null, null, null, null, null, null, "陕西", "甘肃", "青海", "宁夏", "新疆", null, null, null, null, null, "台湾", null, null, null, null, null, null, null, null, null, "香港", "澳门", null, null, null, null, null, null, null, null, "国外" };
            double iSum = 0;
            string info = "";
            System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(@"^\d{17}(\d|x)$");
            System.Text.RegularExpressions.Match mc = rg.Match(cid);
            if (!mc.Success)
            {
                return false;
            }
            cid = cid.ToLower();
            cid = cid.Replace("x", "a");
            if (aCity[int.Parse(cid.Substring(0, 2))] == null)
            {
                return false;//"非法地区";
            }
            try
            {
                DateTime.Parse(cid.Substring(6, 4) + "-" + cid.Substring(10, 2) + "-" + cid.Substring(12, 2));
            }
            catch
            {
                return false;//"非法生日";
            }
            for (int i = 17; i >= 0; i--)
            {
                iSum += (System.Math.Pow(2, i) % 11) * int.Parse(cid[17 - i].ToString(), System.Globalization.NumberStyles.HexNumber);
            }
            if (iSum % 11 != 1)
                return false;// ("非法证号");

            return true;// (aCity[int.Parse(cid.Substring(0, 2))] + "," + cid.Substring(6, 4) + "-" + cid.Substring(10, 2) + "-" + cid.Substring(12, 2) + "," + (int.Parse(cid.Substring(16, 1)) % 2 == 1 ? "男" : "女"));

        }

        private void txtSSO_Leave(object sender, EventArgs e)
        {
            string sso = this.txtSSO.Text.Trim();
            if(!string.IsNullOrEmpty(sso))
            {
                LoginFormService loginFormService = new LoginFormService();
                WorkerCache workerCache = loginFormService.GetWorkerCache(sso);

                if(workerCache != null)
                {
                    this.txtName.Text = workerCache.WorkerName;
                }
                else
                {
                    this.txtName.Text = "";
                }
            }
            
        }
    }
}
